/**
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 * 可变帧率验证Demo
 * 
 * 三个Demo分别验证：
 * - Demo1: 高帧率(60fps) - 快速动画，速度 > 120px/s
 * - Demo2: 中帧率(30fps) - 中速动画，30-120px/s
 * - Demo3: 低帧率(15fps) - 慢速动画，速度 < 30px/s
 *
 * @format
 */

'use strict';

import React, {useRef, useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Animated,
  Easing,
  ScrollView,
} from 'react-native';

/**
 * Demo1: 高帧率验证 (60fps)
 * 
 * 快速位移动画：300px / 0.5s = 600px/s > 120px/s
 * 使用线性缓动确保恒定速度
 * 预期：使用60fps高帧率
 */
export function HighFrameRateDemo() {
  const translateX = useRef(new Animated.Value(0)).current;
  const [frameCount, setFrameCount] = useState(0);
  const [actualFps, setActualFps] = useState(0);
  const [isAnimating, setIsAnimating] = useState(false);
  const frameCountRef = useRef(0);
  const startTimeRef = useRef(0);
  const lastValueRef = useRef(0);
  const velocitiesRef = useRef([]);

  const startAnimation = () => {
    translateX.setValue(0);
    frameCountRef.current = 0;
    startTimeRef.current = Date.now();
    lastValueRef.current = 0;
    velocitiesRef.current = [];
    setIsAnimating(true);

    let lastTime = Date.now();

    // 监听动画值变化来计算帧数和速度
    const listenerId = translateX.addListener(({value}) => {
      frameCountRef.current++;
      const now = Date.now();
      const deltaTime = (now - lastTime) / 1000;
      const deltaValue = Math.abs(value - lastValueRef.current);
      
      if (deltaTime > 0) {
        velocitiesRef.current.push(deltaValue / deltaTime);
      }
      
      lastTime = now;
      lastValueRef.current = value;
    });

    // 快速动画：300px在500ms内完成 = 600px/s（使用线性缓动）
    Animated.timing(translateX, {
      toValue: 300,
      duration: 500,
      easing: Easing.linear, // 使用线性缓动确保恒定速度
      useNativeDriver: false,
    }).start(({finished}) => {
      translateX.removeListener(listenerId);
      const elapsed = Date.now() - startTimeRef.current;
      const fps = (frameCountRef.current / elapsed) * 1000;
      const avgVelocity = velocitiesRef.current.length > 0 
        ? velocitiesRef.current.reduce((a, b) => a + b, 0) / velocitiesRef.current.length 
        : 0;
      
      setFrameCount(frameCountRef.current);
      setActualFps(fps);
      setIsAnimating(false);
      console.log(`[高帧率Demo] 帧数: ${frameCountRef.current}, 耗时: ${elapsed}ms, 实际FPS: ${fps.toFixed(1)}, 平均速度: ${avgVelocity.toFixed(1)}px/s`);
    });
  };

  return (
    <View style={[styles.demoContainer, {borderLeftColor: '#00ff88'}]}>
      <Text style={styles.title}>Demo1: 高帧率验证 (60fps)</Text>
      <Text style={styles.description}>
        快速动画: 300px / 500ms = 600px/s {'\n'}
        阈值: 速度 {'>'} 120px/s 触发60fps
      </Text>
      
      <View style={styles.animationArea}>
        <Animated.View
          style={[
            styles.box,
            styles.boxHigh,
            {transform: [{translateX}]},
          ]}
        />
      </View>

      <TouchableOpacity 
        style={[styles.button, styles.buttonHigh]} 
        onPress={startAnimation}
        disabled={isAnimating}
      >
        <Text style={styles.buttonText}>
          {isAnimating ? '动画中...' : '开始高速动画'}
        </Text>
      </TouchableOpacity>

      <View style={styles.resultContainer}>
        <Text style={styles.result}>
          实际帧数: {frameCount}
        </Text>
        <Text style={styles.result}>
          预期帧数: ~30帧 (60fps × 0.5s)
        </Text>
        <Text style={[styles.result, actualFps > 50 ? styles.resultSuccess : styles.resultWarning]}>
          实际FPS: {actualFps.toFixed(1)}
        </Text>
      </View>
    </View>
  );
}

/**
 * Demo2: 中帧率验证 (30fps)
 * 
 * 中速位移动画：150px / 2s = 75px/s，在30-120px/s之间
 * 使用线性缓动确保恒定速度
 * 预期：使用30fps中帧率
 */
export function MidFrameRateDemo() {
  const translateX = useRef(new Animated.Value(0)).current;
  const [frameCount, setFrameCount] = useState(0);
  const [actualFps, setActualFps] = useState(0);
  const [isAnimating, setIsAnimating] = useState(false);
  const frameCountRef = useRef(0);
  const startTimeRef = useRef(0);
  const lastValueRef = useRef(0);
  const velocitiesRef = useRef([]);

  const startAnimation = () => {
    translateX.setValue(0);
    frameCountRef.current = 0;
    startTimeRef.current = Date.now();
    lastValueRef.current = 0;
    velocitiesRef.current = [];
    setIsAnimating(true);

    let lastTime = Date.now();

    const listenerId = translateX.addListener(({value}) => {
      frameCountRef.current++;
      const now = Date.now();
      const deltaTime = (now - lastTime) / 1000;
      const deltaValue = Math.abs(value - lastValueRef.current);
      
      if (deltaTime > 0) {
        velocitiesRef.current.push(deltaValue / deltaTime);
      }
      
      lastTime = now;
      lastValueRef.current = value;
    });

    // 中速动画：150px在2000ms内完成 = 75px/s（使用线性缓动）
    Animated.timing(translateX, {
      toValue: 150,
      duration: 2000,
      easing: Easing.linear, // 使用线性缓动确保恒定速度
      useNativeDriver: false,
    }).start(({finished}) => {
      translateX.removeListener(listenerId);
      const elapsed = Date.now() - startTimeRef.current;
      const fps = (frameCountRef.current / elapsed) * 1000;
      const avgVelocity = velocitiesRef.current.length > 0 
        ? velocitiesRef.current.reduce((a, b) => a + b, 0) / velocitiesRef.current.length 
        : 0;
      
      setFrameCount(frameCountRef.current);
      setActualFps(fps);
      setIsAnimating(false);
      console.log(`[中帧率Demo] 帧数: ${frameCountRef.current}, 耗时: ${elapsed}ms, 实际FPS: ${fps.toFixed(1)}, 平均速度: ${avgVelocity.toFixed(1)}px/s`);
    });
  };

  return (
    <View style={[styles.demoContainer, {borderLeftColor: '#ffaa00'}]}>
      <Text style={styles.title}>Demo2: 中帧率验证 (30fps)</Text>
      <Text style={styles.description}>
        中速动画: 150px / 2000ms = 75px/s {'\n'}
        阈值: 30px/s {'<'} 速度 {'<'} 120px/s 触发30fps
      </Text>
      
      <View style={styles.animationArea}>
        <Animated.View
          style={[
            styles.box,
            styles.boxMid,
            {transform: [{translateX}]},
          ]}
        />
      </View>

      <TouchableOpacity 
        style={[styles.button, styles.buttonMid]} 
        onPress={startAnimation}
        disabled={isAnimating}
      >
        <Text style={styles.buttonText}>
          {isAnimating ? '动画中...' : '开始中速动画'}
        </Text>
      </TouchableOpacity>

      <View style={styles.resultContainer}>
        <Text style={styles.result}>
          实际帧数: {frameCount}
        </Text>
        <Text style={styles.result}>
          预期帧数: ~60帧 (30fps × 2s)
        </Text>
        <Text style={[styles.result, (actualFps > 25 && actualFps < 40) ? styles.resultSuccess : styles.resultWarning]}>
          实际FPS: {actualFps.toFixed(1)}
        </Text>
      </View>
    </View>
  );
}

/**
 * Demo3: 低帧率验证 (15fps)
 * 
 * 慢速位移动画：60px / 3s = 20px/s < 30px/s
 * 使用线性缓动确保恒定速度
 * 预期：使用15fps低帧率
 */
export function LowFrameRateDemo() {
  const translateX = useRef(new Animated.Value(0)).current;
  const [frameCount, setFrameCount] = useState(0);
  const [actualFps, setActualFps] = useState(0);
  const [isAnimating, setIsAnimating] = useState(false);
  const frameCountRef = useRef(0);
  const startTimeRef = useRef(0);
  const lastValueRef = useRef(0);
  const velocitiesRef = useRef([]);

  const startAnimation = () => {
    translateX.setValue(0);
    frameCountRef.current = 0;
    startTimeRef.current = Date.now();
    lastValueRef.current = 0;
    velocitiesRef.current = [];
    setIsAnimating(true);

    let lastTime = Date.now();

    const listenerId = translateX.addListener(({value}) => {
      frameCountRef.current++;
      const now = Date.now();
      const deltaTime = (now - lastTime) / 1000;
      const deltaValue = Math.abs(value - lastValueRef.current);
      
      if (deltaTime > 0) {
        velocitiesRef.current.push(deltaValue / deltaTime);
      }
      
      lastTime = now;
      lastValueRef.current = value;
    });

    // 慢速动画：60px在3000ms内完成 = 20px/s（使用线性缓动）
    Animated.timing(translateX, {
      toValue: 60,
      duration: 3000,
      easing: Easing.linear, // 使用线性缓动确保恒定速度
      useNativeDriver: false,
    }).start(({finished}) => {
      translateX.removeListener(listenerId);
      const elapsed = Date.now() - startTimeRef.current;
      const fps = (frameCountRef.current / elapsed) * 1000;
      const avgVelocity = velocitiesRef.current.length > 0 
        ? velocitiesRef.current.reduce((a, b) => a + b, 0) / velocitiesRef.current.length 
        : 0;
      
      setFrameCount(frameCountRef.current);
      setActualFps(fps);
      setIsAnimating(false);
      console.log(`[低帧率Demo] 帧数: ${frameCountRef.current}, 耗时: ${elapsed}ms, 实际FPS: ${fps.toFixed(1)}, 平均速度: ${avgVelocity.toFixed(1)}px/s`);
    });
  };

  return (
    <View style={[styles.demoContainer, {borderLeftColor: '#ff4466'}]}>
      <Text style={styles.title}>Demo3: 低帧率验证 (15fps)</Text>
      <Text style={styles.description}>
        慢速动画: 60px / 3000ms = 20px/s {'\n'}
        阈值: 速度 {'<'} 30px/s 触发15fps
      </Text>
      
      <View style={styles.animationArea}>
        <Animated.View
          style={[
            styles.box,
            styles.boxLow,
            {transform: [{translateX}]},
          ]}
        />
      </View>

      <TouchableOpacity 
        style={[styles.button, styles.buttonLow]} 
        onPress={startAnimation}
        disabled={isAnimating}
      >
        <Text style={styles.buttonText}>
          {isAnimating ? '动画中...' : '开始慢速动画'}
        </Text>
      </TouchableOpacity>

      <View style={styles.resultContainer}>
        <Text style={styles.result}>
          实际帧数: {frameCount}
        </Text>
        <Text style={styles.result}>
          预期帧数: ~45帧 (15fps × 3s)
        </Text>
        <Text style={[styles.result, (actualFps > 10 && actualFps < 20) ? styles.resultSuccess : styles.resultWarning]}>
          实际FPS: {actualFps.toFixed(1)}
        </Text>
      </View>
    </View>
  );
}

/**
 * 综合Demo页面
 */
export default function FrameRateDemoScreen() {
  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
      <Text style={styles.header}>可变帧率验证Demo</Text>
      <Text style={styles.subHeader}>
        基于人眼视觉感知的自适应帧率优化
      </Text>
      
      <View style={styles.thresholdInfo}>
        <Text style={styles.thresholdTitle}>帧率切换阈值：</Text>
        <Text style={styles.thresholdText}>• 高帧率 60fps: 速度 {'>'} 120px/s</Text>
        <Text style={styles.thresholdText}>• 中帧率 30fps: 30px/s {'<'} 速度 {'<'} 120px/s</Text>
        <Text style={styles.thresholdText}>• 低帧率 15fps: 速度 {'<'} 30px/s</Text>
      </View>
      
      <HighFrameRateDemo />
      <MidFrameRateDemo />
      <LowFrameRateDemo />
      
      <View style={styles.footer}>
        <Text style={styles.footerText}>
          提示：观察控制台日志获取详细帧率数据
        </Text>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a2e',
  },
  contentContainer: {
    padding: 16,
    paddingBottom: 32,
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#eee',
    textAlign: 'center',
    marginBottom: 8,
  },
  subHeader: {
    fontSize: 14,
    color: '#888',
    textAlign: 'center',
    marginBottom: 16,
  },
  thresholdInfo: {
    backgroundColor: '#0f3460',
    borderRadius: 10,
    padding: 12,
    marginBottom: 20,
  },
  thresholdTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 8,
  },
  thresholdText: {
    fontSize: 12,
    color: '#aaa',
    marginBottom: 4,
  },
  demoContainer: {
    backgroundColor: '#16213e',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    borderLeftWidth: 4,
  },
  title: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 4,
  },
  description: {
    fontSize: 12,
    color: '#aaa',
    marginBottom: 12,
    lineHeight: 18,
  },
  animationArea: {
    height: 60,
    backgroundColor: '#0f0f23',
    borderRadius: 8,
    marginBottom: 12,
    justifyContent: 'center',
    overflow: 'hidden',
  },
  box: {
    width: 50,
    height: 50,
    borderRadius: 8,
    marginLeft: 5,
  },
  boxHigh: {
    backgroundColor: '#00ff88',
    shadowColor: '#00ff88',
    shadowOffset: {width: 0, height: 0},
    shadowOpacity: 0.5,
    shadowRadius: 10,
  },
  boxMid: {
    backgroundColor: '#ffaa00',
    shadowColor: '#ffaa00',
    shadowOffset: {width: 0, height: 0},
    shadowOpacity: 0.5,
    shadowRadius: 10,
  },
  boxLow: {
    backgroundColor: '#ff4466',
    shadowColor: '#ff4466',
    shadowOffset: {width: 0, height: 0},
    shadowOpacity: 0.5,
    shadowRadius: 10,
  },
  button: {
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: 'center',
    marginBottom: 12,
  },
  buttonHigh: {
    backgroundColor: '#00aa55',
  },
  buttonMid: {
    backgroundColor: '#cc8800',
  },
  buttonLow: {
    backgroundColor: '#cc3344',
  },
  buttonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  resultContainer: {
    backgroundColor: '#0f0f23',
    borderRadius: 8,
    padding: 10,
  },
  result: {
    fontSize: 12,
    color: '#88aaff',
    textAlign: 'center',
    marginBottom: 4,
  },
  resultSuccess: {
    color: '#00ff88',
    fontWeight: 'bold',
  },
  resultWarning: {
    color: '#ffaa00',
    fontWeight: 'bold',
  },
  footer: {
    marginTop: 8,
    alignItems: 'center',
  },
  footerText: {
    fontSize: 11,
    color: '#666',
    fontStyle: 'italic',
  },
});

